#include "mimetypemanager.h"

#include <QtCore/QFileInfo>
#include <QtCore/QUrl>

using namespace core;

MimeTypeManager* mimeTypeManager = 0;

MimeTypeManager* MimeTypeManager::getInstance()
{
    if (mimeTypeManager == 0)
    {
        mimeTypeManager = new MimeTypeManager();
    }

    return mimeTypeManager;
}

void MimeTypeManager::destroy()
{
    delete mimeTypeManager;
    mimeTypeManager = 0;
}

void MimeTypeManager::registerMimeType(const MimeType& type)
{
    Q_ASSERT(type.isValid());

    if (!m_registeredMimeTypes.contains(type.name()))
    {
        m_registeredMimeTypes[type.name()] = type;
    }
}

void MimeTypeManager::unregisterMimeType(const MimeType& type)
{
    Q_ASSERT(type.isValid());

    if (m_registeredMimeTypes.contains(type.name()))
    {
        m_registeredMimeTypes.remove(type.name());
    }
}

MimeType MimeTypeManager::mimeType(const QString& name) const
{
    MimeType ret;

    if (m_registeredMimeTypes.contains(name))
    {
        ret = m_registeredMimeTypes[name];
    }

    return ret;
}

MimeType MimeTypeManager::mimeTypeForUrl(const QUrl& url) const
{
    MimeType ret;

    const QString filePath = url.toLocalFile();
    QFileInfo info(filePath);

    if (info.exists())
    {
        const QString suffix = info.suffix();

        foreach (const MimeType& mime, m_registeredMimeTypes)
        {
            if (mime.suffixes().contains(suffix))
            {
                ret = mime;
                break;
            }
        }
    }

    // TODO: add support for other storages than FS

    return ret;
}

MimeTypeManager::MimeTypeManager() :
    m_registeredMimeTypes()
{

}

MimeTypeManager::~MimeTypeManager()
{

}

uint qHash(const core::MimeType& type)
{
    return qHash(type.type()) ^ qHash(type.iconName()) ^
        qHash(type.comment()) ^ qHash(type.filterString());
}
